package com.mr3chi.horoscopes;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.todddavies.components.progressbar.ProgressWheel;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentTarotCard extends Fragment{
	private ProgressWheel 	mLoadBar;
	private RelativeLayout 	mContent;
	
	private TextView tvTopTitle;
	private TextView tvTopCardName;
	
	private TextView tvCardTitle;
	private TextView tvCardDate;
	private TextView tvCardContent;
	
	private TarotLoadingTask task = null;
	private boolean isDone;
	private AlertDialog dialog;
	
	private BroadcastReceiver br = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			FragmentTarotCard.this.receivedBroadcast(intent);
		}
	};
	
	private void receivedBroadcast(Intent i) {
		if(((ActivityMain)getActivity()).hasConnection()){
			if(!isDone){
				if(!dialog.isShowing()){
					dialog.show();
				}
			}
		}
    }
	
	@Override
	public void onPause() {
		super.onPause();
		getActivity().unregisterReceiver(br);
	}

	@Override
	public void onResume() {
		super.onResume();
		IntentFilter iff = new IntentFilter();
		iff.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		getActivity().registerReceiver(br, iff);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_tarotcard, container, false);
		
		mLoadBar = (ProgressWheel) view.findViewById(R.id.fragment_todaycard_loader);
		mLoadBar.spin();
		mContent = (RelativeLayout) view.findViewById(R.id.fragment_todaycard_info);
		
		tvTopTitle = (TextView) view.findViewById(R.id.fragment_todaycard_top_title);
		tvTopTitle.setText("TODAY CARD");
		tvTopCardName = (TextView) view.findViewById(R.id.fragment_todaycard_top_desc);
		
		tvCardTitle = (TextView) view.findViewById(R.id.fragment_todaycard_card_title);
		tvCardTitle.setText("Today Card Meaning");
		tvCardDate = (TextView) view.findViewById(R.id.fragment_todaycard_card_date);
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("MMM, dd yyyy", Locale.US);
		String temp = "System time : " + sdf.format(cal.getTime());
		tvCardDate.setText(temp);
		tvCardContent = (TextView) view.findViewById(R.id.fragment_todaycard_card_desc);
		
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle(R.string.receiver_has_internet_title);
		builder.setMessage(R.string.receiver_has_internet_summary);
		builder.setPositiveButton(R.string.dialog_yes, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				parseTarotCard();
			}

		});
		builder.setNegativeButton(R.string.dialog_no, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		dialog = builder.create();
	
		isDone = true;
		parseTarotCard();
		
		AdView adView = (AdView)view.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
		setHasOptionsMenu(true);
		return view;
	}
	
	public void parseTarotCard() {
		if(((ActivityMain)getActivity()).hasConnection()){
			setLoading(true);
	        task = new TarotLoadingTask();
	        task.execute((Void) null);
        } else {
        	Toast.makeText(getActivity(), R.string.error_no_intenet_connection, Toast.LENGTH_SHORT).show();
        	setLoading(false);
        	mContent.setVisibility(View.GONE);
        	isDone = false;
        }
	}
	
	public void setLoading(boolean load){
		if(load){
			if(mLoadBar.getVisibility()==View.VISIBLE) return;
			else{
				mLoadBar.setVisibility(View.VISIBLE);
				mContent.setVisibility(View.GONE);
				mLoadBar.spin();
			}
		}else{
			if(mLoadBar.getVisibility()==View.GONE) return;
			else{
				mLoadBar.setVisibility(View.GONE);
				mContent.setVisibility(View.VISIBLE);
				mLoadBar.stopSpinning();
			}
		}
	}
	
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_fragment_tarot, menu);
	}

	public class TarotLoadingTask extends AsyncTask<Void, Void, List<String>>{
		
		public TarotLoadingTask() {
			
		}
		
		@Override
		protected List<String> doInBackground(Void... params) {
			String ur 			= "http://m.dailyhoroscope.com/tarot/tarot-card-of-the-day";
			List<String> rs 	= new ArrayList<String>();
			String cardName 	= "";
			String cardMeaning 	= "";
			Document doc;
			try {
				URL url = new URL(ur);
				doc 	= Jsoup.parse(url.openStream(),"UTF-8",ur);
				
				Elements nodes = doc.select("h3.otd-heading");
				if(nodes != null && nodes.size() > 0){
					cardName = nodes.first().text();
				}
				
				nodes = doc.select("div.inner");
				if(nodes != null && nodes.size() > 0){
					cardMeaning = nodes.first().text();
				}
				
				rs.add(cardName);
				rs.add(cardMeaning);
	    		return rs;
	    		
			} catch (IOException e) {
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setLoading(true);
		}

		@Override
		protected void onPostExecute(List<String> result) {
			super.onPostExecute(result);
			if(result == null || result.size() != 2){
				Toast.makeText(getActivity(), R.string.error_notarot_here_yet, Toast.LENGTH_SHORT).show();
				if(!((ActivityMain)getActivity()).hasConnection()){
					isDone = false;
				}
				setLoading(false);
				mContent.setVisibility(View.GONE);
			}else{
				tvTopCardName.setText(result.get(0));
				tvCardContent.setText(Html.fromHtml(result.get(1),null,null));
				if(mContent.getVisibility() != View.VISIBLE) mContent.setVisibility(View.VISIBLE);
				setLoading(false);
				isDone = true;
			}
			
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			setLoading(false);
			task = null;
		}
	}
	
}
